import React, { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import { Canvas } from "@tarojs/components";

function wrapEvent(e) {
  if (!e) return;
  if (!e.preventDefault) {
    e.preventDefault = function () {};
  }
  return e;
}

export default ({ className, style, id, onInit }) => {
  const [currentChart, setCurrentChart] = useState("");
  const [canvasEl, seCanvasEl] = useState("");
  console.log("onInit", onInit);

  const onWxCanvas = () => {
    const query = Taro.createSelectorQuery();
    query
      .select("#" + id)
      .fields({
        node: true,
        size: true,
      })
      .exec((res) => {
        const { node, width, height } = res[0];
        const context = node.getContext("2d");
        const pixelRatio = Taro.getSystemInfoSync().pixelRatio;
        // 高清设置
        node.width = width * pixelRatio;
        node.height = height * pixelRatio;
        //  chart全局设置
        const appendPadding = 5;
        const config = { context, width, height, pixelRatio, appendPadding };
        const chart = onInit(config);

        if (chart) {
          const CH = chart;
          const El = chart.get("el");
          setCurrentChart(CH);
          seCanvasEl(El);
        }
      });
  };
  useEffect(() => {
    setTimeout(() => {
      onWxCanvas();
    }, 500);
  }, []);

  const touchStart = (e) => {
    if (canvasEl) {
      canvasEl.dispatchEvent("touchstart", wrapEvent(e));
    }
  };

  const touchMove = (e) => {
    e.stopPropagation();
    e.preventDefault();
    if (canvasEl) {
      canvasEl.dispatchEvent("touchmove", wrapEvent(e));
    }
  };

  const touchEnd = (e) => {
    if (canvasEl) {
      canvasEl.dispatchEvent("touchend", wrapEvent(e));
    }
  };

  return (
    <Canvas
      className={className}
      style={style}
      type="2d"
      id={id}
      onTouchStart={touchStart}
      onTouchMove={touchMove}
      onTouchEnd={touchEnd}
    />
  );
};
